import { defineStore } from 'pinia'
import { authAPI } from '@/api/auth'

export const useUserStore = defineStore('user', {
    state: () => ({
        // 用户信息
        user: null,
        // 访问令牌
        accessToken: null,
        // 是否已登录
        isLoggedIn: false
    }),

    getters: {
        // 获取用户ID
        userId: (state) => state.user?.id,
        // 获取用户名
        username: (state) => state.user?.username,
        // 检查是否已登录
        isAuthenticated: (state) => state.isLoggedIn && !!state.accessToken
    },

    actions: {
        // 登录
        async login(credentials) {
            try {
                const response = await authAPI.login(credentials)

                if (response.access_token && response.user) {
                    // 保存用户信息和token
                    this.user = response.user
                    this.accessToken = response.access_token
                    this.isLoggedIn = true

                    // 持久化存储到本地
                    this.saveToStorage()

                    console.log('登录成功:', response)
                    return { success: true, data: response }
                } else {
                    throw new Error('登录响应格式错误')
                }
            } catch (error) {
                console.error('登录失败:', error)
                return {
                    success: false,
                    error: error.data?.message || error.message || '登录失败'
                }
            }
        },


        // 登出
        logout() {
            this.user = null
            this.accessToken = null
            this.isLoggedIn = false

            // 清除本地存储
            this.clearStorage()

            console.log('用户已登出')
        },

        // 从本地存储恢复用户状态
        restoreFromStorage() {
            try {
                const userData = uni.getStorageSync('userData')
                if (userData) {
                    const { user, accessToken, isLoggedIn } = JSON.parse(userData)
                    this.user = user
                    this.accessToken = accessToken
                    this.isLoggedIn = isLoggedIn
                    console.log('从本地存储恢复用户状态:', { user, isLoggedIn })
                }
            } catch (error) {
                console.error('恢复用户状态失败:', error)
                this.clearStorage()
            }
        },

        // 保存到本地存储
        saveToStorage() {
            try {
                const userData = {
                    user: this.user,
                    accessToken: this.accessToken,
                    isLoggedIn: this.isLoggedIn
                }
                uni.setStorageSync('userData', JSON.stringify(userData))
                console.log('用户状态已保存到本地存储')
            } catch (error) {
                console.error('保存用户状态失败:', error)
            }
        },

        // 清除本地存储
        clearStorage() {
            try {
                uni.removeStorageSync('userData')
                console.log('本地存储已清除')
            } catch (error) {
                console.error('清除本地存储失败:', error)
            }
        },

        // 检查token是否有效（可选，用于应用启动时验证）
        async validateToken() {
            if (!this.accessToken) {
                return false
            }

            try {
                // 这里可以调用一个验证token的接口
                // const response = await request.get('/auth/validate')
                // return response.valid
                return true // 暂时返回true，实际项目中应该验证token
            } catch (error) {
                console.error('Token验证失败:', error)
                this.logout()
                return false
            }
        }
    }
})
